// store/index.js
import { createStore } from 'vuex';
import axios from 'axios';
export default createStore({
  state() {
    return {
      isAuthenticated: false,
      userRole: 'guest' ,
      account:null,
      token: null
    };
  },
  mutations: {
    SET_AUTH_STATUS(state, status) {
      state.isAuthenticated = status;
    },
    SET_USER_ROLE(state, role) {
      state.userRole = role;
    },
    SET_ACCOUNT(state, account) {
      state.account = account;
    },
    setToken(state, token) {
      state.token = token;
    },
  },


  actions: {
    login({ commit }, payload) {
      return axios.post('/api/login', payload)
        .then(response => {
          const { token, role,submitter_id} = response.data;
          commit('SET_AUTH_STATUS', true);
          commit('SET_USER_ROLE', role);
          commit('SET_ACCOUNT', submitter_id);
          commit('SET_TOKEN', token);
          console.log('submitter_id:', submitter_id);
          localStorage.setItem('token', token);
          localStorage.setItem('userRole', role);
          localStorage.setItem('token', token);
          // this.$router.push('/home2');
        })
        .catch(error => {
          console.error('Login failed:', error);
        });
    },
    logout({ commit }) {
      commit('SET_AUTH_STATUS', false);
      commit('SET_USER_ROLE', 'guest');
      commit('SET_TOKEN', null);
      localStorage.removeItem('token');
      localStorage.removeItem('userRole');
    }
  }
});
